package com.cdp.web.controller.system.fileController;
import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.SysUserFile;
import com.cdp.common.utils.SecurityUtils;
import com.cdp.system.service.ISysUserFileService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private ISysUserFileService sysUserFileService;

    @Value("${filePython.upload-directory}")
    private  String  uploadDirectory;




    /**
     * 上传文件到服务器
     *
     * @param file 上传的文件
     * @return 返回上传结果
     */
    @PostMapping("/upload")
    @Transactional
    public HashMap<String, Object> upload(@RequestParam("file") MultipartFile file) {
        // 指定上传目录
       // String realPath = "C:\\Users\\Administrator\\Desktop\\2\\";
        String realPath =  uploadDirectory;
         // Linux 兼容的文件路径
       // String realPath = "/data/uploadsExcel/"; // 修改为实际的 Linux 目录

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return AjaxResult.error("上传失败，文件名为空");
        }

        // 获取文件扩展名
        String fileExtension = "";
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex != -1) {
            fileExtension = originalFilename.substring(dotIndex).toLowerCase();
        }

        // 生成唯一文件名
        String uniqueFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 6) + fileExtension;

        // 确保上传目录存在
        File uploadDir = new File(realPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 目标文件路径
        File dest = new File(realPath + File.separator + uniqueFileName);

        FileInputStream fileInputStream = null;
        XSSFWorkbook workbook = null;
        try {
            // 保存文件
            file.transferTo(dest);

            // 读取 Excel
            fileInputStream = new FileInputStream(dest);
            workbook = new XSSFWorkbook(fileInputStream);
            Sheet sheet = workbook.getSheetAt(0);
            System.out.println("成功读取 Sheet1：" + sheet.getSheetName());

            // 获取第一行数据
            Row firstRow = sheet.getRow(0);
            List<String> firstRowData = new ArrayList<>();

            if (firstRow != null) {
                // 只读取第 23 列（索引 22）及其之后的单元格
                int firstColumnIndex = 159;
                for (int i = firstColumnIndex; i < firstRow.getLastCellNum(); i++) {
                    Cell cell = firstRow.getCell(i);
                    if (cell != null) {
                        switch (cell.getCellType()) {
                            case STRING:
                                firstRowData.add(cell.getStringCellValue());
                                break;
                            case NUMERIC:
                                firstRowData.add(String.valueOf(cell.getNumericCellValue()));
                                break;
                            case BOOLEAN:
                                firstRowData.add(String.valueOf(cell.getBooleanCellValue()));
                                break;
                            default:
                                firstRowData.add("UNKNOWN");
                        }
                    } else {
                        firstRowData.add("EMPTY");
                    }
                }
            } else {
                return AjaxResult.error("文件中没有数据！");
            }

            // 插入数据库
           // Long userId = SecurityUtils.getUserId();
            SysUserFile userFile = new SysUserFile();
            userFile.setFileUrl(realPath + uniqueFileName);
            userFile.setUserId(0L);
            userFile.setCreateTime(LocalDateTime.now());
           // userFile.setOtherData(firstRowData.toString());
            try {
                sysUserFileService.save(userFile);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
// 获取不带扩展名的文件名
            String nameWithoutExtension = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            HashMap<String, Object> map = new HashMap<>();
            map.put("fileFirstData", firstRowData);
            map.put("url", realPath + uniqueFileName);
            map.put("name", nameWithoutExtension);
            map.put("msg", "操作成功");
            map.put("code", 200);

            return map;

        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件读取失败：" + e.getMessage());
        } finally {
            // 关闭资源
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }





}
